/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState } from 'react';
import { message, Popover, Spin } from 'antd';
import request from '@/utils/request';

interface PreViewPopover {
  api: string;
  name?: string;
  queryData: any;
  text?: string;
  trigger?: string;
  children?: any;
}
const KbPreViewPopover = (props: PreViewPopover) => {
  const { children, name = '', text, api, queryData, trigger = 'click' } = props;
  const [open, setOpen] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [content, setContent] = useState<string>('');

  const onOpenChange = (status: boolean) => {
    if (status) {
      setLoading(true);
      request(api, {
        method: 'POST',
        data: queryData,
      }).then((res) => {
        setLoading(false);
        const { code, data, msg } = res;
        if (code == 0) {
          setOpen(true);
          const value = name ? data[name] : data;
          setContent(value);
        } else {
          message.error(msg);
        }
      });
    } else {
      setOpen(false);
      setContent('');
    }
  };

  return (
    <Spin spinning={loading}>
      {children || text ? (
        <Popover content={content} open={open} onOpenChange={onOpenChange} trigger={trigger}>
          {children || text}
        </Popover>
      ) : (
        '-'
      )}
    </Spin>
  );
};

export default KbPreViewPopover;
